from sqlalchemy import select, and_
from domain.models.models import UserReg
from domain.models.models import Activity
from domain.models.models import Address
from db.db import async_session
import json
async def update_reg_status(user_id: int, activity_id: int, status: int) -> tuple[bool, str]:
    """更新活动报名记录状态
    Args:
        user_id: 用户ID
        activity_id: 活动ID
        status: 状态值
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            # 查询活动报名记录
            stmt = select(UserReg).where(and_(UserReg.user_id == user_id, UserReg.activity_id == activity_id))
            result = await session.execute(stmt)
            reg = result.scalar()

            if not reg:
                return False, "报名记录不存在"

            # 更新活动报名记录状态
            reg.status = status
            # 获取活动信息
            activity = await session.get(Activity, activity_id)
            if activity:
                current_joiners = activity.joiners_ids.split(',') if activity.joiners_ids else []
                
                if status == 1:  # 取消报名
                    if str(user_id) in current_joiners:
                        current_joiners.remove(str(user_id))
                elif status == 0:  # 重新报名
                    if str(user_id) not in current_joiners:
                        current_joiners.append(str(user_id))
                        
                activity.joiners_ids = ','.join(current_joiners) if current_joiners else ''

            await session.commit()
            return True, "更新成功"
        except Exception as e:
            await session.rollback()
            return False, str(e)

async def create_reg(user_id: int, activity_id: int) -> tuple[bool, str]:
    """创建活动报名记录
    Args:
        user_id: 用户ID
        activity_id: 活动ID
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            
            # 创建新的报名记录
            reg = UserReg(
                user_id=user_id,
                activity_id=activity_id,
                status=0  # 0表示报名成功
            )
            
            session.add(reg)
            
            # 更新活动的报名人数列表
            activity = await session.get(Activity, activity_id)
            if activity:
                current_joiners = activity.joiners_ids.split(',') if activity.joiners_ids else []
                if str(user_id) not in current_joiners:
                    current_joiners.append(str(user_id))
                    activity.joiners_ids = ','.join(current_joiners)
            
            await session.commit()
            return True, "报名成功"
            
        except Exception as e:
            await session.rollback()
            return False, str(e)
async def get_user_regs(user_id: int, page: int = 1, page_size: int = 10, 
                       activity_type: str = None, area: str = None, people: str = None) -> tuple[bool, dict]:
    """获取用户报名的活动列表
    Args:
        user_id: 用户ID
        page: 页码
        page_size: 每页数量
        activity_type: 活动类型筛选
        area: 地区筛选
        people: 人数筛选
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            # 构建基础查询条件
            conditions = [
                UserReg.user_id == user_id,
                UserReg.is_delete == 0,
                Activity.is_delete == 0
            ]
            print(activity_type, area, people)
            # 添加活动类型筛选
            if activity_type:
                conditions.append(Activity.type == activity_type)
            
            # 添加地区筛选
            if area:
                conditions.append(Address.name.like(f'%{area}%'))
            
            # 添加人数筛选
            if people:
                if people == '2人':
                    conditions.append(Activity.people_number == 2)
                elif people == '3-5人':
                    conditions.append(and_(Activity.people_number >= 3, Activity.people_number <= 5))
                elif people == '6-10人':
                    conditions.append(and_(Activity.people_number >= 6, Activity.people_number <= 10))
                elif people == '10人以上':
                    conditions.append(Activity.people_number > 10)
            
            # 构建查询语句
            stmt = select(UserReg, Activity, Address).join(
                Activity, UserReg.activity_id == Activity.id
            ).join(
                Address, Activity.address_id == Address.id
            ).where(
                and_(*conditions)
            ).order_by(
                UserReg.c_time.desc()
            ).offset(
                (page - 1) * page_size
            ).limit(page_size)
            
            result = await session.execute(stmt)
            
            # 获取总数
            count_stmt = select(UserReg).join(
                Activity, UserReg.activity_id == Activity.id
            ).join(
                Address, Activity.address_id == Address.id
            ).where(
                and_(*conditions)
            )
            total = len((await session.execute(count_stmt)).all())
            
            activities = []
            for reg, activity, address in result:
                activities.append({
                    "id": activity.id,
                    "name": activity.name,
                    "content": activity.content,
                    "type": activity.type,
                    "images": json.loads(activity.images) if activity.images else [],
                    "address": {
                        "id": address.id,
                        "name": address.name,
                        "address": address.address,
                        "longitude": address.longitude,
                        "latitude": address.latitude
                    },
                    "people_number": activity.people_number,
                    "people_age": activity.people_age,
                    "fee": activity.fee,
                    "start_time": activity.start_time,
                    "end_time": activity.end_time,
                    "status": activity.status,
                    "reg_status": reg.status,
                    "created_user_id": activity.created_user_id,
                    "c_time": reg.c_time.strftime('%Y-%m-%d %H:%M:%S')
                })
            
            return True, {
                "total": total,
                "list": activities
            }
            
        except Exception as e:
            return False, str(e)